import Vue from 'vue';
import Router from 'vue-router';
import home from './home';
// import test from './test';

Vue.use(Router);

const router = new Router({
    routes: [
        {
            path: '/',
            redirect: '/index'
        }, {
            path: '*',
            redirect: '/404',
            meta: {title: '默认为404页面'}
        }, {
            path: '/404',
            component: resolve => require(['../views/404.vue'], resolve),
            meta: {title: '页面没有找到'}
        }, {
            path: '/403',
            component: resolve => require(['../views/403.vue'], resolve),
            meta: {title: '没有权限'}
        }, {
            path: '/login',
            component: resolve => require(['../views/Login.vue'], resolve)
        }, {
            path: '/',
            component: resolve => require(['../views/Home.vue'], resolve),
            meta: {title: '自述文件'},
            children: [
                ...home
            ]
        },
    ]
});


// 使用钩子函数对路由进行权限跳转
router.beforeEach((to, from, next) => {
    const token = sessionStorage.getItem('x_asia_tasty_access_token');
    const role = sessionStorage.getItem('x_asia_tasty_login_role');
    if ((!token || !role) && to.path !== '/login') {
        next('/login');
    } else if (to.meta.permission) {
        //权限控制
        to.meta.permission.indexOf(role) === -1 ? next('/403') : next();
    } else {
        // 简单的判断IE10及以下不进入富文本编辑器，该组件不兼容
        if (navigator.userAgent.indexOf('MSIE') > -1 && to.path === '/editor') {
            Vue.prototype.$alert('vue-quill-editor组件不兼容IE10及以下浏览器，请使用更高版本的浏览器查看', '浏览器不兼容通知', {
                confirmButtonText: '确定'
            });
        } else {
            next();
        }
    }
});


/**
 * 页面跳转之后处理
 */
router.afterEach((to, from, next) => {
    window.scrollTo(0, 0);      //使页面能返回顶部
});


export default router;
